
const Service = require('egg').Service
class UserService extends Service {
  // 获取用户信息
  async myInfo() {
    const { ctx } = this
    // 查询
    const data = await ctx.find('User', {
      attributes: ['id', 'username', 'nickname', 'headIcon', 'phone', 'email'],
      where: {
        id: ctx.state.userInfo.id
      }
    })
    const userInfo = data.dataValues
    return { userInfo }
  }
  // 修改个人信息
  async modifyInfo(body) {
    const { ctx } = this
    const { nickname, phone, email, signature } = body
    const res = await ctx.update('User', { nickname, phone, email, signature }, {
      where: {
        id: ctx.state.userInfo.id
      }
    })
    return res
  }
  // 获取用户列表
  async getUserList(query) {
    const { ctx } = this
    const { username, nickname } = query
    let where = {}
    // 添加模糊字段
    const fuzzyField = { nickname, username }
    where = ctx.helper.addFuzzyField(fuzzyField, where)
    const attributes = { exclude: ['createTime', 'createUser', 'lastTime', 'lastUser', 'deleteFlag'] }
    const options = { where, attributes }
    const res = await ctx.pageFind('User', query, options)
    return res
  }
  // 删除用户
  async deleteUser(id) {
    const { ctx } = this
    const res = ctx.delete('User', {
      where: { id }
    })
    return res ? 1 : 0
  }
}

module.exports = UserService
